<template>
    <div>
        <vxe-toolbar>
            <template #buttons>
                <div class="toolbar-buttons">
                    <el-button @click="openNewExtractionDialog">新增抽取</el-button>
                    <el-input v-model="searchQuery" style="width: 300px;" placeholder="输入名称搜索"
                        @change="filterExtractions" />
                    <el-button @click="fetchExtractions">查询</el-button>
                </div>
            </template>
        </vxe-toolbar>

        <vxe-grid ref="extractionGrid" border show-header :data="filteredExtractions" :columns="columns"
            :row-config="{ isCurrent: true, isSelected: true, isHover: true }" @current-change="selectRow">
            <template #action="{ row }">
                <el-button link type="primary" @click="deleteExtraction(row)">删除</el-button>
                <el-button link type="primary" @click="openExtractionExpertDialog(row)">抽取</el-button>
            </template>
        </vxe-grid>
        <el-divider>抽取专家结果</el-divider>
        <!-- 抽取专家列表 -->
        <vxe-grid border show-header :data="selectedRow" :columns="expertColumns" title="抽取专家列表" />

        <NewExtractionDialog ref="newExtractionDialog" @ExtractionCreated="fetchExtractions" />
    </div>
</template>

<script setup>
import { deleteExtractionById, genExtractionResultByExtractionId, getAllExtractions, getAllProfessions, getExtractionResultByExtractionId } from '@/alova/api';
import NewExtractionDialog from '@/components/NewExtractionDialog.vue';
import { ElLoading, ElMessage } from 'element-plus';
import { ref } from 'vue';

const loading = ref(false);
const searchQuery = ref('')
const selectedRow = ref([])
const extractionList = ref([])
const filteredExtractions = ref([])
const newExtractionDialog = ref(null);
const extractionGrid = ref(null);
const professionList = ref([]);
const columns = ref([
    { field: 'id', title: '序号', width: 60 },
    { field: 'project', title: '项目', formatter: ({ cellValue }) => cellValue?.name || '' },
    { field: 'currentProfession', title: '目前从事专业', width: 200 , formatter: ({ cellValue }) => cellValue.name },
    { field: 'selectionCount', title: '抽取人数', width: 80 },
    {
        field: 'selectionDateTime', title: '抽取时间', width: 80, formatter: ({ cellValue }) => {
            const date = new Date(cellValue);
            const formattedDate = date.toLocaleString('zh-CN', { hour12: false })
                .replace(/\//g, '-');
            return formattedDate;
        }
    },
    { title: '操作', field: 'action', slots: { default: 'action' }, width: 120 }
]);

const getProfessions = async()=>{
    loading.value = true; // 开始加载
    const loader = ElLoading.service({
        fullscreen: true,
        text: "数据加载中...",
    });
    getAllProfessions().then(data => {
        loading.value = false;
        professionList.value = data;
    }).catch(error => {
        console.error("查询失败:", error);
    }).finally(() => {
        loading.value = false; // 结束加载
        loader.close(); // 关闭加载动画
    }); 
};

getProfessions();

const expertColumns = ref([
    { field: 'id', title: '序号', width: 80 },
    { field: 'name', title: '姓名', editor: { type: 'text' } },
    { field: 'idCardNumber', title: '身份证号', editor: { type: 'text' } },
    { field: 'title', title: '职称', editor: { type: 'text' } },
    { field: 'education', title: '最高学历', editor: { type: 'text' } },
    { field: 'majorStudied', title: '所学专业', editor: { type: 'text' } , formatter: ({ cellValue }) => cellValue.name },
    { field: 'currentProfession', title: '目前从事专业', editor: { type: 'text' } , formatter: ({ cellValue }) => cellValue.name },
    { field: 'birthDate', title: '出生年月', editor: { type: 'text' } },
    { field: 'companyName', title: '单位名称', editor: { type: 'text' } },
    { field: 'position', title: '职务', editor: { type: 'text' } },
    { field: 'companyAddress', title: '单位地址', editor: { type: 'text' } },
    { field: 'phoneNumber', title: '联系电话', editor: { type: 'text' } },
    { field: 'postalCode', title: '邮政编码', editor: { type: 'text' } },
    { field: 'mobile', title: '手机', editor: { type: 'text' } },
    { field: 'email', title: '电子邮箱', editor: { type: 'text' } }
]);

// 选中行时，展示其专家信息
const handleRowClick = ({ row }) => {
    if (selectedRow.rowId == row.id) {
        return;
    }
    console.log('选中的行数据:', row)
    loading.value = true; // 开始加载
    const loader = ElLoading.service({
        fullscreen: true,
        text: "数据加载中...",
    });
    selectedRow.value = [];
    selectedRow.rowId = row.id;
    getExtractionResultByExtractionId(row.id).then(data => {
        loading.value = false;
        for (const item of data) {
            selectedRow.value.push(item.expert);
        }
    }).catch(error => {
        console.error("查询用户失败:", error);
    }).finally(() => {
        loading.value = false; // 结束加载
        loader.close(); // 关闭加载动画
    });
}

const openNewExtractionDialog = () => {
    newExtractionDialog.value.openDialog();
};

const selectRow = ({ row }) => {
    handleRowClick({ row });
};

const openExtractionExpertDialog = (row) => {
    console.log('专家抽取中:', row)
    loading.value = true; // 开始加载
    const loader = ElLoading.service({
        fullscreen: true,
        text: "专家抽取中...",
    });
    genExtractionResultByExtractionId(row.id).then(data => {
        loading.value = false;
        selectedRow.value = [];
        for (const item of data) {
            selectedRow.value.push(item.expert);
        }
    }).catch(error => {
        console.error("专家抽取失败:", error.message);
        ElMessage.warning(error.message);
    }).finally(() => {
        loading.value = false; // 结束加载
        loader.close(); // 关闭加载动画
    });
};

const fetchExtractions = () => {
    loading.value = true; // 开始加载
    const loader = ElLoading.service({
        fullscreen: true,
        text: "数据加载中...",
    });
    getAllExtractions().then(data => {
        loading.value = false;
        extractionList.value = data;
        filteredExtractions.value = [...extractionList.value]
    }).catch(error => {
        console.error("查询用户失败:", error);
    }).finally(() => {
        loading.value = false; // 结束加载
        loader.close(); // 关闭加载动画
    });
}

const filterExtractions = () => {
    filteredExtractions.value = extractionList.value.filter(extraction => {
        const result = extraction.project&&extraction.project.name.includes(searchQuery.value) ||
            extraction.currentProfession&&extraction.currentProfession.includes(searchQuery.value)

        return result;
    })

    extractionGrid.value.setCurrentRow(null);
    selectedRow.value = [];
}

const deleteExtraction = (row) => {
    loading.value = true; // 开始加载
    const loader = ElLoading.service({
        fullscreen: true,
        text: "数据删除中...",
    });
    deleteExtractionById(row.id).then(() => {
        loading.value = false;
        fetchExtractions();
    }).catch(error => {
        console.error("删除失败:", error);
    }).finally(() => {
        loading.value = false; // 结束加载
        loader.close(); // 关闭加载动画
    });
}

fetchExtractions();
</script>

<style scoped>
.toolbar-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>